#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUF_SIZE 1024
#define SMALL_BUF 100

void error_handling(char *message);
void *handling_request(void *arg);
void send_data(int sock, char *buf, char *file);
char *get_context_type(char *file);
void send_error(int sock);

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Usage : %s <port> \n", argv[0]);
    }

    int serv_sock, clnt_sock;
    struct sockaddr_in serv_adr, clnt_adr;
    int clnt_adr_sz;

    int str_len;
    char buf[BUF_SIZE];

    pthread_t t_id;

    serv_sock = socket(PF_INET, SOCK_STREAM, 0);
    if (serv_sock == -1)
        error_handling("socket error\n");

    memset(&serv_adr, 0, sizeof(serv_adr));
    serv_adr.sin_family = AF_INET;
    serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_adr.sin_port = htons(atoi(argv[1]));

    if (bind(serv_sock, (struct sockaddr *)&serv_adr, sizeof(serv_adr)) == -1)
        error_handling("bind error\n");

    if (listen(serv_sock, 5) == -1)
        error_handling("listen error\n");

    while (1)
    {
        clnt_adr_sz = sizeof(clnt_adr);
        clnt_sock = accept(serv_sock, (struct sockaddr *)&clnt_adr, &clnt_adr_sz);
        if (clnt_sock == -1)
            continue;
        printf("Client Connected IP : %s, port: %d \n", inet_ntoa(clnt_adr.sin_addr), ntohs(clnt_adr.sin_port));

        pthread_create(&t_id, NULL, handling_request, &clnt_sock);
        pthread_detach(t_id);
    }
    close(serv_sock);
    return 0;
}

void *handling_request(void *arg)
{
    int clnt_sock = *((int *)arg);
    char buf[BUF_SIZE];
    char method[SMALL_BUF];
    char file_name[BUF_SIZE];
    char ct[BUF_SIZE];

    read(clnt_sock, buf, BUF_SIZE);
    if (strstr(buf, "HTTP/") == NULL)
    {
        send_error(clnt_sock);
        close(clnt_sock);
        return NULL;
    }

    strcpy(method, strtok(buf, " /")); // GET
    if (strcmp(method, "GET"))
    {
        send_error(clnt_sock);
        close(clnt_sock);
        return NULL;
    }
    strcpy(file_name, strtok(NULL, " /"));   // index.html
    strcpy(ct, get_context_type(file_name)); // text/html | text/plain
    shutdown(clnt_sock, SHUT_RD);
    send_data(clnt_sock, ct, file_name);
    return NULL;
}

void send_data(int sock, char *ct, char *file)
{
    char protocol[] = "HTTP/1.0 200 OK \r\n";
    char server[] = "Server:Linux Web Server \r\n";
    char cnt_len[] = "Content-length:2048 \r\n";
    char cnt_type[SMALL_BUF];
    char buf[BUF_SIZE];
    FILE *send_file;

    sprintf(cnt_type, "Content-type:%s\r\n\r\n", ct);
    if ((send_file = fopen(file, "r")) == NULL)
    {
        send_error(sock);
        return;
    }

    write(sock, protocol, strlen(protocol));
    write(sock, server, strlen(server));
    write(sock, cnt_len, strlen(cnt_len));
    write(sock, cnt_type, strlen(cnt_type));

    while (fgets(buf, BUF_SIZE, send_file))
        write(sock, buf, strlen(buf));

    close(sock);
}

void send_error(int sock)
{
    char protocol[] = "HTTP/1.0 400 Bad Request \r\n";
    char server[] = "Server:Linux Web Server \r\n";
    char cnt_len[] = "Content-length:2048 \r\n";
    char cnt_type[] = "Content-type:text/html\r\n\r\n";
    char content[] = "<html><head><title>NETWORK</title></head>"
                     "<body><font size=+5><br> 错误！滚蛋"
                     "</font></body></html>";

    write(sock, protocol, strlen(protocol));
    write(sock, server, strlen(server));
    write(sock, cnt_len, strlen(cnt_len));
    write(sock, cnt_type, strlen(cnt_type));
    write(sock, content, strlen(content));
    close(sock);
}

char *get_context_type(char *file)
{
    char extension[SMALL_BUF];
    char file_name[SMALL_BUF];
    strcpy(file_name, file);
    strtok(file_name, ".");
    strcpy(extension, strtok(NULL, "."));
    if (!strcmp(extension, "html") || !strcmp(extension, "htm"))
        return "text/html";
    else
        return "text/plain";
}

void error_handling(char *message)
{
    fputs(message, stdout);
    fputc('\n', stdout);
    exit(-1);
}
